<template>
  <div class="widget-view">
    <template v-if="widget.options.displayType === 'card'">
      <div class="widget_flex_container">
        <div v-if="widget.options.showLabel" class="widget_flex_title">
          {{ widget.name }}
        </div>
        <div class="flex_container">
          <div
            v-for="(column, colIndex) in widget.columns"
            :key="`${widget.key}$${colIndex}`"
            class="sub_form"
          >
            <div v-if="widget.options.showSubLabel" class="sub_form_title">
              {{ widget.name + (colIndex + 1) }}
            </div>
            <div class="sub_form_body">
              <genetate-form-item
                v-for="item in column.list"
                :key="item.key"
                :rules="rules"
                :widget="item"
                :remote="remote"
              />
            </div>
            <div
              v-if="widget.options.operational && widget.columns.length > 1"
              class="flex_container_operation"
            >
              <el-button type="text" @click="del(colIndex)">
                <i class="el-icon el-icon-delete"></i>
              </el-button>
            </div>
          </div>
          <div v-if="widget.options.operational" class="widget_flex_operation">
            <el-button type="text" @click="add">
              {{ $t('fm.actions.add') }}
            </el-button>
          </div>
        </div>
      </div>
    </template>
    <template v-if="widget.options.displayType === 'table'">
      <div class="widget_table_container">
        <div class="flex_table_top">
          <div v-if="widget.options.showLabel" class="flex_table_title">
            {{ widget.name }}
          </div>
          <div
            v-if="!widget.options.disabled && widget.options.operational"
            class="flex_table_operation"
          >
            <el-button type="primary" round @click="addTableRowDataHandle">
              添加
            </el-button>
          </div>
        </div>
        <el-table :data="tableData" border stripe>
          <el-table-column
            v-for="col in tableColumns"
            :key="`table-column-${col.id}`"
            :label="col.label"
            :width="col.width"
            align="center"
          >
            <template slot-scope="scope">
              <div>
                {{ convert(scope.row, col.id) }}
              </div>
            </template>
          </el-table-column>
          <el-table-column
            v-if="!widget.options.disabled"
            label="操作"
            align="center"
          >
            <template slot-scope="scope">
              <div>
                <el-button
                  type="text"
                  size="mini"
                  @click="handleEdit(scope.row, scope.$index)"
                >
                  编辑
                </el-button>
                <el-button
                  v-if="
                    widget.options.operational &&
                    tableData &&
                    tableData.length > 1
                  "
                  type="text"
                  size="mini"
                  @click="handleDelete(scope.$index)"
                >
                  删除
                </el-button>
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-dialog
        :title="`新增${widget.name}`"
        :visible.sync="visible"
        :modal-append-to-body="false"
        width="30%"
        :destroy-on-close="true"
        @close="visible = false"
      >
        <!-- :close-on-click-modal="true" -->
        <el-form
          ref="tableForm"
          :model="tableForm"
          :rules="tableFormRules"
          :inline="false"
          label-width="120px"
          size="medium"
        >
          <genetate-form-item-com
            v-for="item in formWidgetList"
            :key="item.key"
            :rules="rules"
            :widget="item"
            :models="tableForm"
            :remote="remote"
            @change="handleChange"
          />
        </el-form>

        <span slot="footer">
          <el-button type="primary" @click="addTableRowData"> 确认 </el-button>
          <el-button @click="visible = false">取消</el-button>
        </span>
      </el-dialog>
    </template>
  </div>
</template>

<script>
import GenetateFormItemCom from './GenerateFormItemComponent.vue'
import GenetateFormItem from './GenerateFormItem.vue'

export default {
  components: {
    GenetateFormItem,
    GenetateFormItemCom,
  },
  props: ['widget', 'rules', 'remote', 'data'],
  inject: ['models'],
  data() {
    return {
      dataModel: this.models,
      visible: false,
      tableForm: {},
      tableFormRules: {},
      sourceForm: {},
      selectedIndex: -1,
    }
  },
  created() {
    if (this.widget.options.type === 'table') {
      this.initForm()
    }
  },
  computed: {
    tableColumns: {
      get() {
        return this.widget.columns[0].list.map((item) => {
          return {
            id: `${item.type}_${item.key}`,
            label: item.name,
          }
        })
      },
    },
    tableData: {
      get() {
        const arr = []
        const models = this.models
        const tableColumns = this.widget.columns[0].list
        this.widget.columns.forEach((col, index) => {
          const obj = {}
          col.list.forEach((item, subIndex) => {
            obj[`${item.type}_${tableColumns[subIndex].key}`] =
              models[`${item.type}_${item.key}`]
          })
          arr.push(obj)
        })
        return arr
      },
    },
    formWidgetList: {
      get() {
        return this.widget.columns[0].list
      },
    },
  },
  methods: {
    add() {
      const tmp = Object.assign({}, this.widget.columns[0])
      const index = this.widget.columns.length
      tmp.list = tmp.list.map((item) => {
        const modelStr = `${item.type}_${item.key}\$${index}`
        if (item.type === 'blank') {
          this.$set(
            this.models,
            modelStr,
            item.options.defaultType === 'String'
              ? ''
              : item.options.defaultType === 'Object'
              ? {}
              : []
          )
        } else if (
          item.type === 'grid' ||
          item.type === 'tabs' ||
          item.type === 'flexContainer' ||
          item.type === 'divider'
        ) {
          // todo: 原则上只允许一层嵌套，多层嵌套待实现
          const { model, ...others } = item
          return {
            ...others,
            key: `${item.key}\$${index}`,
          }
        } else {
          this.$set(this.models, modelStr, item.options.defaultValue)
        }
        return {
          ...item,
          key: `${item.key}\$${index}`,
          model: `${item.model}\$${index}`,
        }
      })
      this.widget.columns.push(tmp)
    },
    del(index) {
      let tmpColumns = [...this.widget.columns]
      for (let i = index; i < tmpColumns.length - 1; i++) {
        const list = tmpColumns[i].list
        list.forEach((item) => {
          const modelStr = item.model.split('$')[0]
          this.$set(
            this.models,
            item.model,
            this.models[modelStr + '$' + (i + 1)]
          )
        })
      }
      tmpColumns.splice(tmpColumns.length - 1, 1)
      this.$set(this.widget, 'columns', tmpColumns)
      // 删除原数组最后一个
      tmpColumns[0].list.forEach((item) => {
        console.log(this.$delete)
        console.log(`${item.model}\$${tmpColumns.length}`)
        this.$delete(this.models, `${item.model}\$${tmpColumns.length}`)
      })

      console.log('---------------------------')
      console.log(this.widget.columns)
      console.log('---------------------------')
      console.log(this.models)
      console.log('---------------------------')
    },
    addTableRowDataHandle() {
      this.selectedIndex = -1
      this.visible = true
      console.log(this.sourceForm)
      this.tableForm = JSON.parse(JSON.stringify(this.sourceForm))
    },
    addTableRowData() {
      this.visible = false
      this.$refs.tableForm.validate((valid) => {
        if (valid) {
          if (this.selectedIndex < 0) {
            this.addWidget(this.tableForm)
          } else {
            for (var attr in this.tableForm) {
              this.$set(
                this.models,
                this.selectedIndex ? `${attr}$${this.selectedIndex}` : attr,
                JSON.parse(JSON.stringify(this.tableForm[attr]))
              )
            }
          }
        }
      })
    },
    deleteTableRowData(selectedIndex) {
      const length = this.widget.columns.length
      const tmpWidgetColumns = JSON.parse(
        JSON.stringify(this.widget.columns)
      ).slice(0, -1)
      const widgetColumns = this.widget.columns
      for (var i = selectedIndex; i < length - 1; i++) {
        tmpWidgetColumns[i].list.forEach((item, index) => {
          const nextColumnListItem = widgetColumns[i + 1].list[index]
          item.key = `${widgetColumns[0].list[index].key}$${i}`
          this.$set(
            this.models,
            `${item.type}_${item.key}`,
            this.models[`${item.type}_${nextColumnListItem.key}`]
          )
        })
      }
      tmpWidgetColumns[0].list.forEach((item) => {
        this.$delete(this.models, `${item.type}_${item.key}$${length - 1}`)
      })
      this.widget.columns = tmpWidgetColumns
    },
    handleEdit(params, index) {
      this.selectedIndex = index
      this.visible = true
      this.tableForm = JSON.parse(JSON.stringify(params))
    },
    handleDelete(index) {
      this.selectedIndex = index
      this.$confirm('确认删除该数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.deleteTableRowData(index)
          this.$message({
            type: 'success',
            message: '删除成功!',
          })
        })
        .catch((err) => {
          console.log(err)
          this.$message({
            type: 'info',
            message: '已取消删除',
          })
        })
    },
    initForm() {
      this.sourceForm = {}
      this.tableFormRules = {}
      this.widget.columns[0].list.forEach((item) => {
        if (
          item.type === 'checkbox' ||
          (item.type === 'select' && item.options.multiple)
        ) {
          this.sourceForm[`${item.type}_${item.key}`] = []
        } else {
          this.sourceForm[`${item.type}_${item.key}`] = ''
        }
      })
      this.tableForm = JSON.stringify(JSON.stringify(this.sourceForm))
      console.log('this.rules')
      console.log('--------------')
      console.log('--------------')
      console.log(this.rules)
    },
    handleChange({ key, value }) {
      this.$set(this.tableForm, key, value)
    },
    addWidget(params) {
      const sourceWidget = JSON.parse(JSON.stringify(this.widget.columns[0]))
      const addIndex = this.widget.columns.length
      const tmp = sourceWidget.list.map((item, index) => {
        const tmpItem = JSON.parse(JSON.stringify(item))
        tmpItem.key = `${sourceWidget.list[index].key}$${addIndex}`
        const modelValue =
          params[
            `${sourceWidget.list[index].type}_${sourceWidget.list[index].key}`
          ]
        this.$set(
          this.models,
          `${item.type}_${item.key}$${addIndex}`,
          modelValue
        )
        return tmpItem
      })
      sourceWidget.list = tmp
      this.widget.columns.push(sourceWidget)
    },
    convert(params, key) {
      const widgetList = this.widget.columns[0].list
      const type = key.split('_')[0]
      if (type === 'select' || type === 'checkbox' || type === 'radio') {
        // todo: 如果是远程获取数据，需要另行开发
        const options =
          widgetList.find((item) => `${item.type}_${item.key}` === key).options
            .options || []
        if (params[key] instanceof Array) {
          const resultStrArr = []
          params[key].forEach((item) => {
            const tmp = options.find((option) => option.value === item)
            if (tmp) {
              tmp.label
                ? resultStrArr.push(tmp.label)
                : resultStrArr.push(tmp.value)
            }
          })
          return resultStrArr.join(',')
        } else {
          const tmp = options.find((option) => option.value === params[key])
          if (tmp) {
            return tmp.label || tmp.value
          }
        }
      }
      if (typeof params[key] == 'string' || typeof params[key] == 'number') {
        return params[key]
      }
    },
  },
}
</script>

<style lang="scss" scoped>
.widget_flex_container {
  padding: 10px 0;
  display: flex;
  &.active {
    outline-color: #e6a23c !important;
    border-color: #e6a23c !important;
  }
  .widget-view-drag,
  .widget-view-action {
    background: #e6a23c !important;
  }
  .widget-tab-list {
    min-height: 60px;
    background: none;
    border: 1px solid #ccc;
  }
  .flex_container {
    min-height: 50px;
    padding: 10px;
    flex: 1;
  }
  .widget_flex_title {
    font-size: 14px;
    color: #606266;
    padding: 10px 0 20px 20px;
  }
  .sub_form_title {
    font-size: 14px;
    color: #606266;
    padding-right: 10px;
  }
  .sub_form {
    position: relative;
    display: flex;
    margin-top: 15px;
    &:first-child {
      margin: 0;
    }
  }
  .sub_form_body {
    flex: 1;
    background: #f5f5f5;
    padding: 10px 15px;
  }
  .flex_container_operation {
    font-size: 18px;
    padding: 0px 8px;
    .el-button {
      font-size: 16px;
    }
    background: #f5f5f5;
  }
}
.widget_table_container {
  display: flex;
  flex-direction: column;
  .flex_table_top {
    display: flex;
    flex-direction: row;
    justify-content: space-between;
    padding: 10px 0;
    align-items: center;
  }
}
</style>
